package gui.threads;

import gui.Login;
import gui.Main;
import gui.Utils;

import java.sql.SQLException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import LogicSide.Session;

public class LoginThread extends Thread{
		private String username;
		private String password;
		private Session session;
		private Shell shell;
		private Display display;
		public LoginThread(String username, String password, Session session, Shell shell, Display dispaly) {
			super();
			this.username = username;
			this.password = password;
			this.session = session;
			this.shell = shell;
			this.display = dispaly;
		}
		
		@Override
		public void run() {
			Login.done = false;
			this.session = new Session();
			try {
				this.session = LogicSide.Login.executeLogin(
						username,
						password);
			} catch (Exception e) {
				this.display.asyncExec(new Runnable() {
					
					@Override
					public void run() {
						Utils.popUpBox("Error", "No connection", shell);
						Utils.regularCursor(display, shell);
					}
				});
				
				return;
			}
			if (this.session.getUser_id() == 0){
					// TODO give some respectful message
				display.asyncExec(new Runnable() {
					
					@Override
					public void run() {
						shell.setCursor(new Cursor(display, SWT.CURSOR_ARROW));
						Utils.popUpBox("Login failed", "Incorrect username/password", shell);
					}
				});
			}
			else {
				display.asyncExec(new Runnable() {
					public void run() {
						shell.setCursor(new Cursor(display, SWT.CURSOR_ARROW));
						shell.dispose();
						Shell mainShell = Main.createMain(display,
								session);
						mainShell.open();
						mainShell.pack();
						

						while (!mainShell.isDisposed()) {
							if (!display.readAndDispatch()) {
								display.sleep();
							}
						}
						display.dispose();
						session.getCon().closeConnection();
					}
				});
				
			}
		}
	}